package com.zggk.iroad.log.logdbmx;


import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.TimePickerView;
import com.bigkoo.pickerview.listener.CustomListener;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.lxj.matisse.Matisse;
import com.zggk.iroad.R;
import com.zggk.iroad.api.MyAppliCation;
import com.zggk.iroad.db.EntityManager;
import com.zggk.iroad.db.LogInfo;
import com.zggk.iroad.db.LxInfo;
import com.zggk.iroad.greendao.DcLxInfoDao;
import com.zggk.iroad.greendao.LogInfoDao;
import com.zggk.iroad.greendao.LxInfoDao;
import com.zggk.iroad.log.logadd.LogAddJson;
import com.zggk.iroad.mvp.MVPBaseActivity;
import com.zggk.iroad.util.MyUtils;
import com.zggk.iroad.util.NoScroolGridView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * MVPPlugin
 * 邮箱 784787081@qq.com
 */

public class LogDbMxActivity extends MVPBaseActivity<LogDbMxContract.View, LogDbMxPresenter> implements LogDbMxContract.View {

    @Bind(R.id.back)
    ImageView back;
    @Bind(R.id.title_text)
    TextView titleText;
    @Bind(R.id.cancle_button)
    TextView cancleButton;
    @Bind(R.id.jlry_te)
    TextView jlryTe;
    @Bind(R.id.jlry_lay)
    LinearLayout jlryLay;
    @Bind(R.id.xcry_te)
    EditText xcryTe;
    @Bind(R.id.xcry_lay)
    LinearLayout xcryLay;
    @Bind(R.id.lx_te)
    TextView lxTe;
    @Bind(R.id.lx_lay)
    LinearLayout lxLay;
    @Bind(R.id.xcsj_te)
    TextView xcsjTe;
    @Bind(R.id.xcsj_lay)
    LinearLayout xcsjLay;
    @Bind(R.id.xctq_te)
    TextView xctqTe;
    @Bind(R.id.xctq_lay)
    LinearLayout xctqLay;
    @Bind(R.id.xclx_te)
    TextView xclxTe;
    @Bind(R.id.xclx_lay)
    LinearLayout xclxLay;
    @Bind(R.id.xcnr_lay)
    LinearLayout xcnrLay;
    @Bind(R.id.xcnr_et)
    EditText xcnrEt;
    @Bind(R.id.cljl_lay)
    LinearLayout cljlLay;
    @Bind(R.id.cljl_et)
    EditText cljlEt;
    @Bind(R.id.czwt_lay)
    LinearLayout czwtLay;
    @Bind(R.id.czwt_et)
    EditText czwtEt;
    @Bind(R.id.cljy_lay)
    LinearLayout cljyLay;
    @Bind(R.id.cljy_et)
    EditText cljyEt;
    @Bind(R.id.tjtp_lay)
    LinearLayout tjtpLay;
    @Bind(R.id.add_pic_grid)
    NoScroolGridView addPicGrid;
    @Bind(R.id.add_pic_lay)
    LinearLayout addPicLay;
    @Bind(R.id.save_te)
    TextView saveTe;
    @Bind(R.id.add_te)
    TextView addTe;
    @Bind(R.id.add_lay)
    LinearLayout addLay;
    @Bind(R.id.log_add_lay)
    RelativeLayout logAddLay;
    private OptionsPickerView pickerView;

    private String LXMC = "";
    private String LXID = "";

    private String DCMC;
    private String DCID;
    private LogMxGird logMxGird;
    private Map<Integer, LogMxGird> mapAdapter = new HashMap<>();
    private int REQUEST_CODE_CHOOSE = 66;
    private int childViewPosition;//点击拍照获取的childveiw下标
    private LogInfoDao logInfoDao;
    private LogInfo logInfo;
    private LxInfoDao lxInfoDao;
    private DcLxInfoDao dcLxInfoDao;


    public void setChildViewPosition(int childViewPosition) {
        this.childViewPosition = childViewPosition;
    }

    @Override
    public void onRequestError(String msg) {

    }

    @Override
    protected int getLayout() {
        return R.layout.act_log_add;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        initData();
    }

    private void initData() {
        titleText.setText("日志新增");
        lxInfoDao = EntityManager.getInstance().getLxInfoDao();
        dcLxInfoDao = EntityManager.getInstance().getDcLxInfoDao();
        logInfoDao = EntityManager.getInstance().getLogInfoDao();
        logInfo = logInfoDao.loadByRowId(getIntent().getLongExtra("RZID", 0));
        jlryTe.setText(logInfo.getXCJLRY());
        xcryTe.setText(logInfo.getXCRY());
        List<LxInfo> SSS = lxInfoDao.queryBuilder().where(LxInfoDao.Properties.LXID.eq(logInfo.getLXID())).limit(1).list();
        LXMC = SSS.get(0).getLXMC();
        LXID = SSS.get(0).getLXID();
        lxTe.setText(SSS.get(0).getLXMC());
        xcsjTe.setText(logInfo.getXCSJ());
        xctqTe.setText(logInfo.getXCTQ());
        DCMC = logInfo.getDCMC();
        DCID = logInfo.getDCID();
        xclxTe.setText(DCMC);
        xcnrEt.setText(logInfo.getXCNR());
        cljlEt.setText(logInfo.getCLJL());
        czwtEt.setText(logInfo.getCZWT());
        cljyEt.setText(logInfo.getCLJY());
        ArrayList<Drawable> listPicture = new ArrayList<>();
        ArrayList<String> listImgUrl = new ArrayList<>();
        if (!StringUtils.isSpace(logInfo.getTPDZ())) {
            String[] strArr = logInfo.getTPDZ().split(",");
            if (strArr != null && strArr.length > 0) {
                for (int i = 0; i < strArr.length; i++) {
                    String imgUrl = strArr[i];
                    listImgUrl.add(imgUrl);
                    Drawable drawable = new BitmapDrawable();
                    listPicture.add(drawable);
                }
            }
        }
        Drawable addPicture = getResources().getDrawable(R.drawable.img_add_pic);
        listPicture.add(addPicture);
        final int childPosition = addPicLay.getChildCount();
        logMxGird = new LogMxGird(this, listPicture, listImgUrl, childPosition);
        addPicGrid.setAdapter(logMxGird);
        mapAdapter.put(childPosition, logMxGird);
    }

    @OnClick({R.id.back, R.id.lx_lay, R.id.xcsj_lay, R.id.xctq_lay, R.id.xclx_lay, R.id.save_te, R.id.add_te})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.lx_lay:
                List<String> LxDatas = new ArrayList<>();
                for (int i = 0; i < lxInfoDao.loadAll().size(); i++) {
                    LxDatas.add(lxInfoDao.loadAll().get(i).getLXMC());
                }
                setOption(LxDatas, lxTe, 1);
                break;
            case R.id.xcsj_lay:
                TimePickerView ksTimes = new TimePickerView.Builder(LogDbMxActivity.this, new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {//选中事件回调
                        xcsjTe.setText(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date));
                    }
                }).setType(new boolean[]{true, true, true, true, true, true})
                        .build();
                ksTimes.setDate(Calendar.getInstance());
                ksTimes.show();
                break;
            case R.id.xctq_lay:
                List<String> TqDatas = new ArrayList<>();
                TqDatas.add("晴");
                TqDatas.add("阴");
                TqDatas.add("雨");
                TqDatas.add("雪");
                TqDatas.add("雾");
                setOption(TqDatas, xctqTe, 0);
                break;
            case R.id.xclx_lay:
                List<String> DcDatas = new ArrayList<>();
                for (int i = 0; i < dcLxInfoDao.loadAll().size(); i++) {
                    DcDatas.add(dcLxInfoDao.loadAll().get(i).getTEXT());
                }
                setOption(DcDatas, xclxTe, 2);
                break;
            case R.id.save_te:
                LogInfo logInfo = new LogInfo();
                logInfo.setId(getIntent().getLongExtra("RZID", 0));
                logInfo.setGYDW(MyAppliCation.spUtils.getString("GydwMc"));//管养单位
                logInfo.setGYDWID(MyAppliCation.spUtils.getString("GydwId"));//管养ID
                logInfo.setXCJLRY(jlryTe.getText().toString());//记录人员
                logInfo.setXCRY(xcryTe.getText().toString());//巡查人员
                logInfo.setLXMC(LXMC);//巡查路线
                logInfo.setLXID(LXID);//巡查路线
                logInfo.setXCSJ(xcsjTe.getText().toString());//巡查时间
                logInfo.setXCTQ(xctqTe.getText().toString());//巡查天气
                logInfo.setDCMC(DCMC);//巡查名称
                logInfo.setDCID(DCID);//巡查id
                logInfo.setXCNR(xcnrEt.getText().toString());//巡查内容
                logInfo.setCLJL(cljlEt.getText().toString());//处理记录
                logInfo.setCZWT(czwtEt.getText().toString());//存在问题
                logInfo.setCLJY(cljyEt.getText().toString());//处理建议
                String imgStr = "";
                ArrayList<String> listImgUrl = logMxGird.getListImgUrl();
                if (listImgUrl != null && listImgUrl.size() > 0) {
                    for (int k = 0; k < listImgUrl.size(); k++) {
                        if (k == 0) {
                            imgStr += listImgUrl.get(k);
                        } else {
                            imgStr += "," + listImgUrl.get(k);
                        }
                    }
                }
                logInfo.setTPDZ(imgStr);
                logInfo.setISDB("1");
                logInfo.setRZID("");
                logInfoDao.update(logInfo);
                ToastUtils.showShort("添加成功");
                Intent intent = new Intent();
                setResult(2, intent);
                finish();
                break;
            case R.id.add_te:
                LogAddJson logAddJson = new LogAddJson();
                List<LogAddJson.XCRZBean> xcrzBeans = new ArrayList<>();
                LogAddJson.XCRZBean xcrzBean = new LogAddJson.XCRZBean();
                xcrzBean.setCREATOR(MyAppliCation.spUtils.getString("OrgName"));
                xcrzBean.setCREATETIME(new SimpleDateFormat("yyyy/MM/dd").format(new Date()));
                xcrzBean.setMODIFYTIME(new SimpleDateFormat("yyyy/MM/dd").format(new Date()));
                xcrzBean.setGYDW(MyAppliCation.spUtils.getString("GydwId"));
                xcrzBean.setXCXZ(DCID);
                xcrzBean.setXCLD(LXID);
                xcrzBean.setLDMC(LXMC);
                xcrzBean.setXCSJ(xcsjTe.getText().toString());
                xcrzBean.setXCR(xcryTe.getText().toString());
                xcrzBean.setXCNR(xcnrEt.getText().toString());//巡查内容
                xcrzBean.setCLJL(cljlEt.getText().toString());//处理记录
                xcrzBean.setCZWT(czwtEt.getText().toString());//存在问题
                xcrzBean.setCLYQ(cljyEt.getText().toString());//处理建议
                xcrzBean.setYZR("");
                xcrzBean.setYZRQ("");
                xcrzBean.setBZ("");
                xcrzBean.setTQ(xctqTe.getText().toString());
                xcrzBean.setXCQKJL("");
                xcrzBean.setDCLX("");
                String imgStr2 = "";
                ArrayList<String> listImgUrl2 = logMxGird.getListImgUrl();
                if (listImgUrl2 != null && listImgUrl2.size() > 0) {
                    for (int k = 0; k < listImgUrl2.size(); k++) {
                        if (k == 0) {
                            imgStr2 += listImgUrl2.get(k);
                        } else {
                            imgStr2 += "," + listImgUrl2.get(k);
                        }
                    }
                }
                if (!StringUtils.isSpace(imgStr2)) {
                    String[] strArr = imgStr2.split(",");
                    if (strArr != null && strArr.length > 0) {
                        ArrayList<LogAddJson.PICBean> listPic = new ArrayList<>();
                        for (int i = 0; i < strArr.length; i++) {
                            LogAddJson.PICBean picInfo = new LogAddJson.PICBean();
                            String imgUrl = strArr[i];
                            String nameStr = imgUrl.substring(imgUrl.lastIndexOf("/") + 1, imgUrl.length());
                            String typeStr = imgUrl.substring(imgUrl.lastIndexOf(".") + 1, imgUrl.length());
                            picInfo.setPicFileName(nameStr);
                            picInfo.setPicFileType(typeStr);
                            String strBlob = MyUtils.bmpToBase64String(imgUrl);
                            picInfo.setPicDataBlob(strBlob);
                            listPic.add(picInfo);
                        }
                        xcrzBean.setPICRZ(listPic);
                    }
                }
                xcrzBeans.add(xcrzBean);
                logAddJson.setXCRZ(xcrzBeans);
                logAddJson.setXCBH("");
                logAddJson.setPFDXX("");
                String json = new Gson().toJson(logAddJson);
                mPresenter.addLog(json, LogDbMxActivity.this);
                break;
        }
    }

    public void setOption(final List<String> datas, final TextView textview, final int type) {
        pickerView = new OptionsPickerView.Builder(LogDbMxActivity.this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                if (type == 1) {//路线
                    LXMC = lxInfoDao.loadAll().get(options1).getLXMC();
                    LXID = lxInfoDao.loadAll().get(options1).getLXID();
                } else if (type == 2) {
                    DCMC = dcLxInfoDao.loadAll().get(options1).getTEXT();
                    DCID = dcLxInfoDao.loadAll().get(options1).getVALUE();
                }
                String tx = datas.get(options1);
                textview.setText(tx);
            }
        }).setLayoutRes(R.layout.progress_lay, new CustomListener() {
            @Override
            public void customLayout(View v) {
                final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                TextView ivCancel = (TextView) v.findViewById(R.id.iv_cancel);
                tvSubmit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        pickerView.returnData();
                        pickerView.dismiss();
                    }
                });
                ivCancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        pickerView.dismiss();
                    }
                });
            }
        }).build();
        pickerView.setPicker(datas);
        pickerView.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {
            final LogMxGird dieaseGridAdapter = mapAdapter.get(childViewPosition);
            final ArrayList<Drawable> listPicture = dieaseGridAdapter.getListPicture();
            final ArrayList<String> listImgUrl = dieaseGridAdapter.getListImgUrl();
            String imgPath = Matisse.obtainCropResult(data);
            listPicture.remove(listPicture.size() - 1);
            Bitmap bitmap = BitmapFactory.decodeFile(imgPath);
            if (bitmap != null) {
                Drawable drawable = new BitmapDrawable(bitmap);
                listPicture.add(drawable);
                listImgUrl.add(imgPath);
                Drawable addPicture = getResources().getDrawable(R.drawable.img_add_pic);
                listPicture.add(addPicture);
                dieaseGridAdapter.notifyDataSetChanged();
            }
        }
    }

    @Override
    public void addLogs(String data) {
        if (data.equals("1")){
            logInfoDao.deleteByKey(getIntent().getLongExtra("RZID", 0));
            ToastUtils.showShort("上传成功");
            Intent intent = new Intent();
            setResult(2, intent);
            finish();
        }

    }
}
